package com.qf.bbapi.intercepet;

import com.alibaba.fastjson.JSON;
import com.qf.bbapi.anno.Token;
import com.qf.bbapi.config.RedisKeyConfig;
import com.qf.bbapi.util.JedisUtil;
import com.qf.bbapi.vo.R;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {
    /*
    * 预拦截
    * 访问之前触发
    * 返回值：true表示放行*/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //验证当前的请求是不是接口
        if(handler instanceof HandlerMethod){
            //强转
            HandlerMethod method=(HandlerMethod) handler;
            //验证当前的接口请求有没有@Token注解
            if(method.hasMethodAnnotation(Token.class)){
                //如果有注解,表示需要登录才能访问
                //获取浏览器中的token
                String token = request.getIntHeader("token")+"";
                //验证redis有没有对应的令牌
                if(JedisUtil.checkKey(RedisKeyConfig.USER_ID+token)){
                    //如果存在，表示已经登录
                    //放行
                    return true;
                }else{
                    //拦截并返回信息
                    //设置响应体的编码格式
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().println(JSON.toJSONString(R.fail("亲，登录失效！")));
                    return false;
                }
            }else{
                return true;
            }
         }
        return true;
    }

    /*
    * 映射方法触发之后执行*/
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /*
    * 整个请求结束*/
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
